package ua.org.enginer.controls.renderers {

import flash.events.Event;

import mx.controls.CheckBox;
import mx.controls.DataGrid;
import mx.controls.listClasses.BaseListData;
import mx.events.FlexEvent;
import mx.events.ListEvent;

public class DataGridSelectionIndicator extends CheckBox {

	public function DataGridSelectionIndicator() {
		super();
		addEventListener(Event.CHANGE, onChange)
		setStyle("paddingLeft", 3)
	}
	
	
	private function onChange(event:Event):void {
		var grid:DataGrid = DataGrid(listData.owner)
		var myIndex:int = grid.itemRendererToIndex(this)

		if (selected) {
			if (grid.selectedIndices.indexOf(myIndex)>=0) return;
			var indices:Array = grid.selectedIndices
			indices.push(myIndex)
			grid.selectedIndices = indices
		}
		else grid.selectedIndices = grid.selectedIndices.filter(function (...args):Boolean {
			if (args[0] == myIndex) return false;
			return true
		})
	}
	
	private function onItemClick(event:Event):void {
		var grid:DataGrid = DataGrid(listData.owner)
		var myIndex:int = grid.itemRendererToIndex(this)
		selected = grid.selectedIndices.indexOf(myIndex)>=0
	}
	
	override public function set listData(value:BaseListData):void {
		super.listData = value
		
		var grid:DataGrid = DataGrid(value.owner)
		
		grid.addEventListener(FlexEvent.VALUE_COMMIT, onItemClick)
		grid.addEventListener(ListEvent.ITEM_CLICK, onItemClick)
		//grid.addEventListener(ListEvent.CHANGE, onItemClick)
		selected = false
	}
	
	override public function set data(value:Object):void {
		// prevent default behavior
	}
}
}

